import { createAction } from 'redux-actions'
import { INIT_USERINFO_TYPE, UPDATE_USERINFO_TYPE, UPDATE_USERINFO_TOKEN_TYPE } from '../types/userinfo'
import DeviceStorage from 'src/utils/DeviceStorage'
import { getAuthToken, getUserInfoByUserId, getUserInfoForB, saveUserInfoToC, saveUserInfoToB } from 'src/utils/RequestAPI'
/**
 * 初始化用户信息
 */
export const INIT_USERINFO_ACTION = createAction(INIT_USERINFO_TYPE, payload => payload)
/**
 * 更新用户信息
 */
export const UPDATE_USERINFO_ACTION = createAction(UPDATE_USERINFO_TYPE, payload => payload)
/**
 * 从本地读取身份类型
 */
export const GET_LOCAL_USERINFO_ACTION = createAction(UPDATE_USERINFO_TYPE, () => {
  return new Promise((resolve) => {
    DeviceStorage.get('userinfo').then(payload => {
      console.log('GET_LOCAL_USERINFO_ACTION', payload)
      resolve(payload)
    })
  })
})
/**
 * 根据phone、codeH或者refresh_token获取token、userId
 */
export const DO_REQUEST_AUTH_TOKEN_ACTION = createAction(UPDATE_USERINFO_TOKEN_TYPE, (args) => {
  return new Promise((resolve, reject) => {
    getAuthToken(args).then(res => {
      const keys = ['access_token', 'refresh_token', 'token_type', 'userId', 'mobile', 'scope']
      const obj = keys.reduce((a, b) => {
        a[b] = res.data[b]
        return a
      }, {})
      resolve(obj)
    }).catch(error => {
      // todo
      const { response: { data } = {} } = error
      reject(data)
    })
  })
})
/**
 * 根据UserId获取C端用户
 */
export const DO_REQUEST_USERINFO_C_ACTION = createAction(UPDATE_USERINFO_TYPE, (args) => {
  return new Promise((resolve, reject) => {
    getUserInfoByUserId(args).then(res => {
      resolve({
        C: res.data
      })
    }).catch(() => {
      reject()
    })
  })
})

/**
 * 保存用户信息C端
 */
export const DO_REQUEST_SAVEUSERINFO_C_ACTION = createAction(UPDATE_USERINFO_TYPE, (args) => {
  return new Promise((resolve, reject) => {
    saveUserInfoToC(args).then(res => {
      resolve({
        C: res.data
      })
    }).catch(() => {
      reject()
    })
  })
})

/**
 * 根据UserId获取B端用户
 */
export const DO_REQUEST_USERINFO_B_ACTION = createAction(UPDATE_USERINFO_TYPE, (args) => {
  return new Promise((resolve, reject) => {
    getUserInfoForB(args).then(res => {
      resolve({
        B: res.data
      })
    }).catch(() => {
      reject()
    })
  })
})

/**
 * 保存用户信息B端
 */
export const DO_REQUEST_SAVEUSERINFO_B_ACTION = createAction(UPDATE_USERINFO_TYPE, (args) => {
  return new Promise((resolve, reject) => {
    saveUserInfoToB(args).then(res => {
      resolve({
        B: res.data
      })
    }).catch(() => {
      reject()
    })
  })
})
